define(function(require, exports, module){
  'use strict';
  var $ = require('jquery');
  require('bootstrapjs')($);
  var SimpleMap = require('seajs/plugs/simpleMap');
  var _const = require('seajs/fn/fnConst');
  var fnModal = require('seajs/fn/fnModal');
  var fnUtils = require('seajs/fn/fnUtils');
  
  var poiIcon = function(category){
    if(category){
    var icon;
      switch(category){
        case _const.DEVICE.DISPATCHER:
          icon = '<i class="fa fa-tv fa-stack-1x fa-inverse"></i>';
          break;
        default:
          icon = '<i class="fa fa-user fa-stack-1x fa-inverse"></i>';
      }
      return icon;
    }
  }

  var poiLable = function(member){
    if(member){
      var lable = [];
      lable.push('<div class="content">');
      lable.push('<div>');
      lable.push(member.memberName);
      lable.push('</div><div>');
      return {
        content: lable.join(''),
        offset: new AMap.Pixel(-48, -27) 
      };
    }
  }

  var createTg = function(_data, success, error){  
    fnUtils.commonPost('group/createTemporaryGroup.do', _data,
      function(rlt){
        if(rlt.status === _const.HTTP.RES_STATUS.SUCCESS){
          if(rlt.error.code === _const.HTTP.RES_STATUS.ERROR_CODE.FAIL){
            if(error){
              error(rlt.error.message);
            }
          }else{
            setTimeout(function(){
              success(rlt);
            }, 2000);
          }
        }else{
          if(error){
            error(rlt.error.message);
          }
        }
      },
      function(e){
        error(e);
      }
    );
  }

  var markerClickEvent = function(contxt, marker){
    contxt.drawInfoWindow(marker);
  }

  var markerInfoWindow = function(contxt, member){
    if(member){
      var offlineFlag = (member.status == _const.IS_ON_LINE.OFF_LINE); //不在线为true
      var infoWindow = document.createElement('div');
      infoWindow.className = 'infoWindow-ext';

      var main = document.createElement('div');
      main.className = 'infoWindow-data';

      var topCloseX = document.createElement('img');
      topCloseX.className = 'close';
      topCloseX.src = 'images/info_close.png';
      topCloseX.onclick = function(){
         if(contxt.infoWindowMap.get(member.memberId)){
           contxt.infoWindowMap.get(member.memberId).close();
         }
      }
      main.appendChild(topCloseX);

      var nameDiv = document.createElement('div');
      nameDiv.innerHTML = '<label>姓名</label>' + '<span style="margin-left: 42px;">' + member.memberName + '</span>';
      main.appendChild(nameDiv);

      var statusStr = offlineFlag?'不在线':'在线';
      var statusDiv = document.createElement('div');
      statusDiv.innerHTML = '<label>状态</label>' + '<span style="margin-left: 42px;">' + statusStr + '</span>';
      main.appendChild(statusDiv);

      var accoutDiv = document.createElement('div');
      accoutDiv.innerHTML = '<label>账号</label>' + '<span style="margin-left: 42px;">' + member.memberCode + '</span>';
      main.appendChild(accoutDiv);
      //
      var currentGDiv = document.createElement('div');
      currentGDiv.innerHTML = '<label>当前群组</label>' + '<span style="margin-left: 14px;" id="groupChange">' + member.inGroupName + '</span>';
      main.appendChild(currentGDiv);

      var locationDiv = document.createElement('div');
      locationDiv.innerHTML = '<label>地理位置</label>' + '<span id="infoWindowLocation" style="margin-left: 14px;">' + contxt.getAddress(member.position, function(address){
                          $('#infoWindowLocation').html(address);
                        }, function(error){
                          $('#infoWindowLocation').html('暂无法获取地理位置');
                          //console.log('无法获取地理位置');
                        }) + '</span>';
      main.appendChild(locationDiv);
      var updateDiv = document.createElement('div');
      var currentTime = member.positionTime?member.positionTime:'';
      updateDiv.innerHTML = '<label>最近一次位置上报时间</label>' + '<span style="margin-left: 10px;" id="nearTime">' + currentTime + '</span>';
      main.appendChild(updateDiv);
      var operationDiv = document.createElement('div');  
      var operationLabel = document.createElement('label'); 
      operationLabel.innerHTML = "操作"; 
      operationDiv.appendChild(operationLabel);
      var operationBtn = document.createElement('div');   
      operationBtn.className = offlineFlag?"infoWindow-single-call-disable":"infoWindow-single-call-enable";
      var creageSingleCall = function(){
        if(contxt.ws.tasks && contxt.ws.tasks.taskMap.size() > 0){
          var status=$('#main_bottom_left_voice_obj').html().slice(0,-1);
          $('#function-alert').html(status+'正在进行,请先关闭'+status+'组在进行其他操作').fadeIn(200,function(){
            setTimeout(function(){
              $('#function-alert').fadeOut(500);
            },1000)
          })
        }else{
          operationBtn.removeEventListener('click', creageSingleCall);
          var data = {
            'userid': parseInt(contxt.ws.uid),
            'userType': _const.DEVICE.DISPATCHER,
            'companyid': parseInt(contxt.ws.cmpid),
            'timestamp': fnUtils.getUnixTime() + '',
            'key': contxt.ws.key,
            'groupType': _const.PTT_TYPE.SINGLE_CALL,   // 单呼
            'memberIds': member.memberId
          };
          createTg(data, function(rlt){
            operationBtn.addEventListener('click', creageSingleCall, false);
            contxt.ws.singleCall(member.memberId, rlt.body);
          }, function(e){
            console.log(e);
          });
        }
      }
      if(!offlineFlag){
        operationBtn.addEventListener('click', creageSingleCall, false);
      }
      operationDiv.appendChild(operationBtn);
      main.appendChild(operationDiv);
      infoWindow.appendChild(main);
      return infoWindow;
    }
  }

  var FnMap = function(){
  	this.map = undefined;
    this.showMemberMap = undefined;
    this.markerMap = undefined;
    this.infoWindowMap = undefined;
    this.ws = undefined;

    this.topMarker = undefined;
    this.mousetool = undefined;
    this.geocoder = undefined;

    this.inMemberMap = undefined;

    this.onlyLat=undefined;
    this.onlyLng=undefined;
  };
FnMap.prototype.cutGroupName='bobobobobobbobo'
  FnMap.prototype.setWs = function(ws){
    if(_const.debug){
      console.log('========== setWs() ==========');
    }
    if(ws){
      this.ws = ws;
    }
  }

  FnMap.prototype.initAmap = function(zoom){
    if(_const.debug){
      console.log('==========','initAmap()','==========');
    }
    this.showMemberMap = new SimpleMap();
    this.markerMap = new SimpleMap();
    this.infoWindowMap = new SimpleMap();
    this.inMemberMap = new SimpleMap();
  	if(this.map){
  	  return;
  	}else{
  	  if(!zoom){
  		  zoom = 14;
  	  }
      this.map = new AMap.Map('container', {
        resizeEnable: true,
        draggable: true,
        zoom: zoom
      });
      this.amapRectangleInit();
      this.mousetoolInit();
      this.autocompleteInit();
      this.geocoderInit();
      return this.map;
  	}
  };

  FnMap.prototype.mousetoolInit = function(_fun){
    var self = this;
    self.map.plugin(["AMap.MouseTool"],function(){
      self.mousetool = new AMap.MouseTool(self.map);
      AMap.event.addListener(self.mousetool, 'draw', function(e){
        for(var i in self.ws.slidebar.memberMap.map){
          if(self.ws.slidebar.memberMap.get(i) !== undefined 
             && self.ws.slidebar.memberMap.get(i).status === _const.IS_ON_LINE.ON_LINE
             && self.markerMap.get(i).getMap()!== null
             && e.obj.contains(new AMap.LngLat(self.ws.slidebar.memberMap.get(i).position[0],
              self.ws.slidebar.memberMap.get(i).position[1]))){
            
            self.inMemberMap.put(self.ws.slidebar.memberMap.get(i).memberId, self.ws.slidebar.memberMap.get(i));
          }
        }

        if(self.inMemberMap.size() > 0){
          self.ws.tasks.temporaryGroup.initSelectDialog(self.ws.slidebar.groupMap.map, self.inMemberMap);
          self.ws.tasks.temporaryGroup.openSelectDialog();
        }
        self.inMemberMap.clear();
        self.map.setDefaultCursor();
        self.amapRectangleInit();
        self.offDrawRectangle();
        self.mousetool.close(true);
      });
    });
  }

  FnMap.prototype.amapRectangleInit = function(){
    var self = this;
    $('#frame-selection').on('click', function(){
      //$(this).off('click');
      if(!self.ws.tasks.currentId){
        self.onDrawRectangle();
      }else{
        var status=$('#main_bottom_left_voice_obj').html().slice(0,-1);
        $('#function-alert').html(status+'正在进行,请先关闭'+status+'组在进行其他操作').fadeIn(200,function(){
          setTimeout(function(){
            $('#function-alert').fadeOut(500);
          },1000)
        })
      }
    });
  }
  FnMap.prototype.autocompleteInit = function(){
    var self = this;
    AMap.plugin(['AMap.Autocomplete','AMap.PlaceSearch','AMap.Geolocation'], function(){
      //zjb change
      var geolocation=new AMap.Geolocation({
        enableHighAccuracy:true,
        covert:true,
        showButton:false,
        panToLocation:true,
        showMarker:false,
        showCircle:false,
        timeout:60000
      })
      geolocation.getCurrentPosition(function(status,result){
        console.log(result);
      });//获取当前位置
      self.map.addControl(geolocation);
      //above zjb change
      var autoOptions = {
        city: "全国", //城市，默认全国
        input: "searchInput"//使用联想输入的input的id
      };
      var autocomplete= new AMap.Autocomplete(autoOptions);
      var placeSearch = new AMap.PlaceSearch({
        city: '全国',
        map: self.map
      });
      AMap.event.addListener(autocomplete, "select", function(e){
        self.map.setCenter(new AMap.LngLat(e.poi.location.lng, e.poi.location.lat));
        self.map.setZoom(12);
      });
      AMap.event.addListener(autocomplete,'complete',function(e){
        if(e.tips){
            if(e.tips[0].location.lat){
              self.onlyLat= e.tips[0].location.lat;
              self.onlyLng= e.tips[0].location.lng;
            }
        }
      });
   });
  }

  FnMap.prototype.geocoderInit = function(){
    var self = this;
    AMap.service('AMap.Geocoder',function(){
      self.geocoder = new AMap.Geocoder({
        city: "010"
      })
    });
  }

  FnMap.prototype.getAddress = function(lnglatXY, success, error){
    var self = this;
    if(self.geocoder){
      self.geocoder.getAddress(lnglatXY, function(status, result) {
        if (status === 'complete' && result.info === 'OK') {
          success(result.regeocode.formattedAddress);
        }else{
          error(null);
        }
      }); 
    }
  }

  FnMap.prototype.onDrawRectangle = function(){
     var self = this;
     self.map.setDefaultCursor('crosshair');
     if(!self.mousetool){
        self.mousetoolInit(function(){
          self.mousetool.rectangle(); 
        });
     }else{
        self.mousetool.rectangle();
     }
  }

  FnMap.prototype.offDrawRectangle = function(){
     var self = this;
     if(self.mousetool){
       self.mousetool.close();
     }
  }
  FnMap.prototype.drawMarker = function(member){
    var slft = this;
    if(member){
      var poi = [], lable = [], marker;
      if(member.status === _const.IS_ON_LINE.OFF_LINE){
        poi.push('<div class="marker-poi uncheck"><img src="images/info_position_offline.png" id="marker_icon_i_' + member.memberId + '"/>');
      }else{
        poi.push('<div class="marker-poi uncheck"><img src="images/info_position_online.png" id="marker_icon_i_' + member.memberId + '"/>');
      }
      poi.push('</div>');
      if(!this.markerMap.get(member.memberId)){
        marker = new AMap.Marker({
          draggable: true,  //是否可拖动
          showShadow: true,
          autoMove: true,
          offset: new AMap.Pixel(-25, -55),
          position: member.position
        });
        AMap.event.addListener(marker, 'click', function(){
          markerClickEvent(slft, this);
        });
      }else{
        marker = this.markerMap.get(member.memberId);
      }

      marker.setExtData(member);
      marker.setLabel(poiLable(member));
      marker.setContent(poi.join(''));
      marker.setMap(this.map);
      this.markerMap.put(member.memberId, marker);
    }
  }
  /**********************************************************************************************************
   *********************************************** 以下拍传地图标识 ********************************************
   **********************************************************************************************************/
  FnMap.prototype.photoSiteMarker=function(log,lat){
    var content = document.createElement('div');
    content.innerHTML = "<div class='pic-site'><div class='inside'>图</div></div>";
    content.className = 'pic-site1';
    var marker = new AMap.Marker({
      content: content,
      offset: new AMap.Pixel(-25, -55),
      position: [log,lat]
    });
    marker.setMap(this.map);
    //this.map.setCenter(log,lat);
    this.map.setCenter(new AMap.LngLat(log,lat));
    this.map.setZoom(12);
    marker.setContent(content);
  };
  /**********************************************************************************************************
   *********************************************** 以上拍传地图标识 ********************************************
   **********************************************************************************************************/
  FnMap.prototype.drawInfoWindow = function(marker){
  	if(marker){
      var infoWindow, member = marker.getExtData();
      console.log(this.ws.slidebar.clickUid);
      if(member){
        //if(this.ws.slidebar.clickUid==member.memberId){
        //  if(this.ws.slidebar.positionTime){member.positionTime=this.ws.slidebar.positionTime;}
        //  if(this.ws.slidebar.latLng){member.position=this.ws.slidebar.latLng}
        //}
        if(this.ws.slidebar.clickUid[member.memberId]){
          if(this.ws.slidebar.clickUid[member.memberId].positionTime){
            member.positionTime=this.ws.slidebar.clickUid[member.memberId].positionTime;
          }
          if(this.ws.slidebar.clickUid[member.memberId].latLng){
            member.latLng=this.ws.slidebar.clickUid[member.memberId].latLng;
          }
        }

        if(this.ws.slidebar.cutUid==member.memberId){
          if(this.ws.slidebar.cutGroupName){member.inGroupName=this.ws.slidebar.cutGroupName;}
        }
        var _infoWindow = markerInfoWindow(this, member);
        if(this.infoWindowMap.get(member.memberId)){
          infoWindow = this.infoWindowMap.get(member.memberId);
          infoWindow.setContent(_infoWindow);
        }else{
          infoWindow = new AMap.InfoWindow({
            isCustom: true, //使用自定义窗体
            content: _infoWindow,
            offset: new AMap.Pixel(-1, -52),
            position: member.position,
            closeWhenClickMap: true
          });
        }
        this.infoWindowMap.put(member.memberId, infoWindow);
        infoWindow.open(marker.getMap(), marker.getPosition());
      }
  	}
  }

  FnMap.prototype.showMarkerPut = function(member){
    this.showMemberMap.put(member.memberId, member);
    this.drawMarker(this.showMemberMap.get(member.memberId));
  }

  FnMap.prototype.showMarkerRemove = function(memberId){
    if(memberId && this.showMemberMap.get(memberId)){
      this.showMemberMap.remove(memberId);
      if(this.showMemberMap.get(memberId)){
        this.drawMarker(this.showMemberMap.get(memberId));
      }else{
        this.markerMap.get(memberId).setMap(null);
      }
    }
  }

  FnMap.prototype.online = function(memberId){
      let marker = this.markerMap.get(memberId);
      if(marker){
        $('#marker_icon_i_' + memberId).attr('src', 'images/info_position_online.png');
      }
    }

    FnMap.prototype.offline = function(memberId){
      let marker = this.markerMap.get(memberId);
      if(marker){
        $('#marker_icon_i_' + memberId).attr('src', 'images/info_position_offline.png');
      }
  }

  FnMap.prototype.clearInfoWindow = function(){
    this.map.clearInfoWindow();
  }

  FnMap.prototype.setTopMarker = function(marker){
    this.topMarker = marker;
  }

  FnMap.prototype.getTopMarker = function(){
    return this.topMarker;
  }
  
  return FnMap;
});